<?php
namespace app\index\model;
/**
 * Created by Submint Text.
 * User: hetaoren<452649510@qq.com>
 * Date: 2017/03/10
 * Explain: 角色志业务处理
 */
class Roles extends Base{
	/**
	 * 分页
	 */
	public function pageQuery(){
		// return $this->where('dataFlag',1)->field('roleId,roleName')->paginate(input('pagesize/d'));
		$page = $this->where('dataFlag',1)->paginate(input('pagesize/d'))->toArray();
		if(count($page['Rows'])>0){
			foreach ($page['Rows'] as $key => $v){
				$page['Rows'][$key]['num'] = model('Staffs')->where(['dataFlag'=>1,'staffRoleId'=>$v['roleId']])->count();
			}
		}
		return $page;
	}
	/**
	 * 列表
	 */
	public function listQuery(){
		return $this->where('dataFlag',1)->field('roleId,roleName')->select();
	}
	/**
	 * 列表
	 */
	public function listQuery2(){
		return $this->where('dataFlag',1)->column('roleId,roleName');
	}
	/**
	 * 删除
	 */
    public function del(){
	    $id = input('post.id/d');
		$data = [];
		$data['dataFlag'] = -1;
	    $result = $this->update($data,['roleId'=>$id]);
        if(false !== $result){
        	return HTRReturn("删除成功", 1);
        }else{
        	return HTRReturn($this->getError());
        }
	}
	
	/**
	 * 获取角色权限
	 */
	public function getById($id){
		return $this->get(['dataFlag'=>1,'roleId'=>$id]);
	}
	
	/**
	 * 新增
	 */
	public function add(){
		$result = $this->validate('Roles.add')->allowField(true)->save(input('post.'));
        if(false !== $result){
        	return HTRReturn("新增成功", 1);
        }else{
        	return HTRReturn($this->getError());
        }
	}
    /**
	 * 编辑
	 */
	public function edit(){
		$id = input('post.roleId/d');
	    $result = $this->validate('Roles.edit')->allowField(true)->save(input('post.'),['roleId'=>$id]);
        if(false !== $result){
            $staffRoleId = (int)session('HTR_STAFF.staffRoleId');
        	if($id==$staffRoleId){
        		$STAFF = session('HTR_STAFF');
        		$STAFF['privileges'] = explode(',',input('post.privileges'));
        		$STAFF['roleName'] = Input('post.roleName');
        		session('HTR_STAFF',$STAFF);
        	}
        	return HTRReturn("编辑成功", 1);
        }else{
        	return HTRReturn($this->getError());
        }
	}
	
}
